package com.example.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@RestController
@DefaultProperties(defaultFallback = "defaultFallback")//设置公共降级方法
public class HystrixController {

//    @HystrixCommand(fallbackMethod = "fallback")
    /*@HystrixCommand(commandProperties = {
        //@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000"),//hystrix超时设置，这里是3秒
        @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),                              //设置熔断
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),              //断路器最小请求数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),       //在熔断这个时间里，降级处理器成为主逻辑
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")             //错误超过60%（链接失败数/circuitBreaker.requestVolumeThreshold），断路器打开
    })*/
    @HystrixCommand()
    @RequestMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam Integer code){
        if(code%2==0){
            return HttpStatus.OK.name();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        RestTemplate restTemplate = new RestTemplate();
        String stringResponseEntity = restTemplate.postForObject("http://localhost:39201/product/listForOrder", Arrays.asList("164103465734242707"), String.class);
//        throw  new RuntimeException("服务异常");
        return stringResponseEntity;
    }

    private String fallback(){

        return "网络请求失败!!";
    }
    private String defaultFallback(){

        return "公共默认提示：网络差!!";
    }
}
